package com.mine.androidlearn.api.Interceptor;

import android.text.TextUtils;


import com.mine.androidlearn.api.sign.ParamKey;
import com.mine.androidlearn.api.sign.SignTool;

import java.io.IOException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


/**
 *
 *
 * @author mine
 * @version V1.0 2018/8/6 22:32
 */
public class HttpSignatureInterceptor implements Interceptor {

    private final static String POST = "POST";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (request.method().equals(POST)) {

            if (request.body() instanceof FormBody) {
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                FormBody formBody = (FormBody) request.body();

                Map<String, String> map = new HashMap<>();
                //把原来的参数添加到新的构造器，（因为没找到直接添加，所以就new新的）
                for (int i = 0; i < formBody.size(); i++) {
                    // Token失效导致重新请求时需要过滤掉前一次的sign参数
                    if (TextUtils.equals(ParamKey.SIGN, formBody.encodedName(i))) {
                        continue;
                    }
                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    map.put(formBody.encodedName(i), URLDecoder.decode(formBody.encodedValue(i), "UTF-8"));
                }

                // 签名
                String securityRandom = String.valueOf(SignTool.getSecurityRandom());
                String timestamp = String.valueOf(System.currentTimeMillis());
                map.put(ParamKey.SECURITY_RANDOM, securityRandom);
                map.put(ParamKey.TIMESTAMP, timestamp);
                map.put(ParamKey.APP_ID, "appid");// TODO: 2018/8/3 question
                String sign = null;
                try {
                    sign = SignTool.createSign(map);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(sign)) {
                    sign = "no_sign";
                }
                // 添加参数
                formBody = bodyBuilder
                        .addEncoded(ParamKey.SECURITY_RANDOM, securityRandom)
                        .addEncoded(ParamKey.TIMESTAMP, timestamp)
                        .addEncoded(ParamKey.APP_ID, "appid")// TODO: 2018/8/3 question
                        .addEncoded(ParamKey.SIGN, sign)
                        .build();

                request = request.newBuilder().post(formBody).build();
            }
        }
        return chain.proceed(request);
    }
}
